## 此为借鉴代码 ，小修改
##  author：zhaomin
# ***

from passlib import pwd
from passlib.context import CryptContext
# 用户密码的处理，包括生成密码、哈希加密和验证密码


pwd_context = CryptContext(schemes=["argon2"], deprecated="auto")

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)


def generate_password() -> str:
    return pwd.genword()



## token的验证等  
import jwt
from datetime import datetime, timedelta
from typing import Optional
from fastapi import HTTPException, status

from app.schemas.base.login import JWTPayload
from app.core.config import settings

### jwt token
def create_access_token(*, data: JWTPayload):
    payload = data.model_dump().copy()
    encoded_jwt = jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
    return encoded_jwt

def verify_token(token: str) -> Optional[JWTPayload]:
    """
    验证JWT token
    Args:
        token: JWT token字符串
    Returns:
        JWTPayload: 解码后的token数据，如果验证失败返回None
    """
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
        # 检查token是否过期
        exp = payload.get("exp")
        if exp:
            exp_datetime = datetime.fromtimestamp(exp)
            if exp_datetime < datetime.now():
                return None
        
        return JWTPayload(**payload)
    except (jwt.DecodeError, jwt.ExpiredSignatureError, ValueError):
        return None


def create_access_token_with_expiry(*, data: dict, expires_delta: Optional[timedelta] = None):
    """
    创建带过期时间的access token
    Args:
        data: 要编码的数据
        expires_delta: 过期时间增量，如果为None则使用默认配置
    Returns:
        str: 编码后的JWT token
    """
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES)
    
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
    return encoded_jwt

